package com.tianlh.service.exam;

/**
 * @author 黑子
 * @Date 2018/1/23 20:25
 */
public class WaitNotify {

    // 锁对象,保证锁的是同一个对象
    final static WaitNotify LOCK_OBJECT = new WaitNotify();

    public static void main(String[] args) {
        // wait 和 notify要放在同步代码块之内，否则会抛异常
        new Thread(new PrintOddTask(0,100)).start();
        new Thread(new PrintEventTask(0, 100)).start();
    }

    public static class PrintEventTask implements Runnable {
        private int evenStartContThreshold;
        private int eventContThreshold;
        int count = evenStartContThreshold;

        // 保留无参构造器
        PrintEventTask() {}

        PrintEventTask(int evenStartContThreshold, int eventContThreshold) {
            this.evenStartContThreshold = evenStartContThreshold;
            this.eventContThreshold = eventContThreshold;
        }

        @Override
        public void run() {
            while (count <= (eventContThreshold - 2)) {
                synchronized (WaitNotify.LOCK_OBJECT) {
                    System.out.println("EventTask: " + (count += 2));
                    WaitNotify.LOCK_OBJECT.notify();
                    try {
                        WaitNotify.LOCK_OBJECT.wait();
                    } catch (InterruptedException e) {
                        System.out.println(e.getMessage());
                    }
                }
            }
        }
    }

    public static class PrintOddTask implements Runnable {

        private int oddStratContThreshold;
        private int oddContThreshold;

        // 保留无参构造器
        PrintOddTask() {}

        PrintOddTask(int oddStratContThreshold, int oddContThreshold) {
            this.oddContThreshold = oddContThreshold;
            this.oddStratContThreshold = oddStratContThreshold;
        }

        int count = oddStratContThreshold - 1;

        @Override
        public void run() {
            while (count <= (oddContThreshold - 2)) {
                synchronized (WaitNotify.LOCK_OBJECT) {
                    System.out.println("OddTask: " + (count += 2));
                    WaitNotify.LOCK_OBJECT.notify();
                    try {
                        WaitNotify.LOCK_OBJECT.wait();
                    } catch (InterruptedException e) {
                        System.out.println(e.getMessage());
                    }
                }
            }
        }
    }
}
